package com.sleepcamel.resteasyConfigurator.util;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class GSONClassFieldSerializer implements JsonSerializer<Class<?>>, JsonDeserializer<Class<?>> {
	    @Override
	    public JsonElement serialize(Class<?> src, Type typeOfSrc, JsonSerializationContext context) {
	        JsonObject result = new JsonObject();
	        result.add("type", new JsonPrimitive(src.getCanonicalName()));
	 
	        return result;
	    }
	 
	    @Override
	    public Class<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
	        JsonObject jsonObject = json.getAsJsonObject();
	        String type = jsonObject.get("type").getAsString();
	 
	        try {
	        	Class<?> classFor = null;//ClassProvider.getInstance().getClassFor(type);
	        	if ( classFor == null ){
	        		classFor = Class.forName(type);
	        	}
	            return classFor;
	        } catch (ClassNotFoundException cnfe) {
	            throw new JsonParseException("Unknown element type: " + type, cnfe);
	        }
	    }
}
